﻿using LxBasic;
using System;

namespace LxCore
{
    public partial class ZoneCFDFields : JsObject
    {
        public ZoneCFDFields(FvZone zone)
        {
            this.Zone = zone;
        }
        //local
        public EquationWithTransTerm Temperature;
        public SIMPLEFields SimpleGroup;
        public SIMPLEPressure Pressure => SimpleGroup?.Pressure;
        public SIMPLEVelocity Velocity => SimpleGroup?.Velocity;
        public MassFluxBase MassFlux => SimpleGroup?.MassFlux;
        public DensityFieldKeeper Density;
        //share
        public FvZone Zone;
        public ZoneCond ZoneCond => ResHelper.GetCond(this.Zone);
        protected PhysicalModel PhysicalModel => ZoneCond.PhysicalModel;
        protected (MaterialProperty matp, ReferenceValue refv, InitialValue iniv, SolveSetting sols) GetPhysicalModelDetail()
        {
            return (PhysicalModel.MaterialProperty, PhysicalModel.ReferenceValue, PhysicalModel.InitialValue, PhysicalModel.SolveSetting);
        }
        public void CheckCreate()
        {
            if (PhysicalModel == null) return;
            CheckCreator.Instance(ref Density);
            Density.CheckCreate(Zone, PhysicalModel.MaterialProperty.Density);
            CheckCreate_Vel();
            CheckCreate_T();
            CheckCreate_TurbBase();
            CheckCreate_kw();
            CheckCreate_Rad();

            SetParameter_Vel();
            SetParameter_T();
            SetParameter_TurbBase();
            SetParameter_kw();
            SetParameter_Rad();
        }
        protected bool CheckCreatAndReuse<TSpecific, TBase>(ref TBase valueNow, out TSpecific newValue) where TSpecific : class, TBase, new() where TBase : ZoneHead
        {
            var old = valueNow;
            bool created = CheckCreator.Instance(ref valueNow, out newValue);
            if (created && old != null)
            {
                newValue.Reuse(old);
            }
            return created;
        }
        public override void FromJsonKV(string key, IJsonReader jsReader)
        {
            switch (key)
            {
                case nameof(Temperature): jsReader.ReadObject(Temperature, e => Temperature = e); break;
                case nameof(SimpleGroup): jsReader.ReadObject(SimpleGroup, e => SimpleGroup = e, t => new SIMPLEFields()); break;
                default: base.FromJsonKV(key, jsReader); break;
            }
        }
        public override void ToJsonKV(IJsonWriter jsWriter)
        {
            base.ToJsonKV(jsWriter);
            if (Temperature != null)
            {
                jsWriter.WriteObject(nameof(Temperature), Temperature, true);
            }
            if (SimpleGroup != null)
            {
                jsWriter.WriteObject(nameof(SimpleGroup), SimpleGroup);
            }
        }
    }
}
